package cipher

import (
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"github.com/obscuren/ecies"
	"math/big"
)

/**
公钥封装接口
只用用来加密和验签
 */
type EccPublicCipher struct {
	eccPubKey *ecdsa.PublicKey
	eciesPubKey *ecies.PublicKey
}


func (e *EccPublicCipher)SetPublicKey(publicKey []byte)(err error){

	var (
		pubKeyBlock      *pem.Block
		pubKey           interface{}
		ok               bool
	)

	// 2. 使用pem解码
	pubKeyBlock, _ = pem.Decode(publicKey)

	// 3. 使用x509解码
	if pubKey, err = x509.ParsePKIXPublicKey(pubKeyBlock.Bytes); err != nil {
		return
	}

	// 4. 转化为ecdsa的pubkey
	if e.eccPubKey, ok = pubKey.(*ecdsa.PublicKey); !ok {
		err = errors.New("获取ecdsa公钥失败")
		return
	}

	// 5. 转化为ecies的pubkey
	e.eciesPubKey = ecies.ImportECDSAPublic(e.eccPubKey)



	return

}
func (e *EccPublicCipher)Encrypt(src []byte) (dst []byte, err error){
	if e.eciesPubKey == nil{
		err = errors.New("ecc.Encrypt没有设置公钥")
		return
	}
	// 6. 加密
	dst, err = ecies.Encrypt(rand.Reader, e.eciesPubKey, src, nil, nil)
	return
}
func (e *EccPublicCipher)VerifySign(src,sig []byte)(isOk bool, err error){
	if e.eccPubKey == nil{
		err = errors.New("RsaPublicCipher.Encrypt没有设置公钥")
		return false,err
	}
	h := sha256.Sum256(src)
	var(
	r                big.Int
	s                big.Int
	)
	// 6. 验证签名
	r.SetBytes(sig[:len(sig)/2])
	s.SetBytes(sig[len(sig)/2:])
	isOk = ecdsa.Verify(e.eccPubKey, h[:], &r, &s)
	if !isOk {
		err = errors.New("验证签名失败")
	}
	return isOk,err
}


